package edu.zut.controller;

import edu.zut.dao.UserDao;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//负责登录的前后端交互
public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设定编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取登录的表单数据
        String user_name = request.getParameter("user_name");
        String user_psw = request.getParameter("user_psw");
        System.out.println("user_name = " + user_name);
        System.out.println("user_psw = " + user_psw);
        String error;
        //验证是否为空？如果为空，返回登录页面，告诉用户输入的用户名或密码不能为空
        if (null == user_name || user_name.trim().length() == 0 || null == user_psw || user_psw.trim().length() == 0) {
            //返回登录页面，告诉用户用户名或密码不能为空
            error = "用户名或密码不能为空";
            request.setAttribute("error", error);
            //转发到登录页面,同时携带错误提示信息
            RequestDispatcher dispatcher = request.getRequestDispatcher("/loginPage");
            dispatcher.forward(request, response);
        } else {
            //验证表单数据是否正确？去数据库验证  -->调用我们数据层（针对数据库的CRUD）的操作
            UserDao userDao = new UserDao();
            boolean result = userDao.userLogin(user_name, user_psw);
            if (result) {
                //登录成功
                request.setAttribute("user_name", user_name);
                request.getRequestDispatcher("/indexPage").forward(request, response);
            } else {
                //登录失败
                error = "用户名或密码不正确";
                request.setAttribute("error", error);
                request.getRequestDispatcher("/loginPage").forward(request, response);
            }
        }
    }
}
